package com.aifeng.common_ui.helper

import android.annotation.SuppressLint
import android.content.Context
import android.provider.Settings
import android.telephony.TelephonyManager

/**
 * 设备工具类
 */

/**
 * IMEI （唯一标识序列号）
 * 需与[.isPhone]一起使用
 * 需添加权限: <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 *
 * @return IMEI
 */
fun Context.getIMEI() = if (isPhone()) getDeviceIdIMEI() else getAndroidId()

/**
 * 判断设备是否是手机
 */
fun Context.isPhone(): Boolean {
    val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    return tm.phoneType != TelephonyManager.PHONE_TYPE_NONE
}

/**
 * 获取设备的IMEI
 * 需添加权限: <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 */
@SuppressLint("HardwareIds", "MissingPermission")
fun Context.getDeviceIdIMEI(): String {
    //android.telephony.TelephonyManager
    val mTelephony = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    @Suppress("DEPRECATION")
    return if (mTelephony.deviceId != null) {
        mTelephony.deviceId
    } else {
        //android.provider.Settings;
        Settings.Secure.getString(
            applicationContext.contentResolver,
            Settings.Secure.ANDROID_ID
        )
    }
}

/**
 * 获取ANDROID ID
 */
@SuppressLint("HardwareIds")
fun Context.getAndroidId(): String = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)

